#include <webx/menu.h>

class ShareNote : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(ShareNote, "/compile/${filename}")

int ShareNote::process()
{
	param_string(id);
	param_string(dbid);
	param_string(title);
	param_string(folder);

	webx::CheckAlnumString(id, 0);
	webx::CheckFileName(title, 0);
	webx::CheckFileName(folder, 0);

	if (id.empty() && title.empty())
	{
		clearResponse();
		
		return XG_PARAMERR;
	}

	try
	{
		checkLogin();
	}
	catch(Exception e)
	{
	}

	string user;
	string level;
	string sqlcmd;
	string content;

	if (id.empty())
	{
		if (folder.empty())
		{
			sqlcmd = "SELECT USER,LEVEL,CONTENT FROM T_XG_CODE WHERE FOLDER='WEBPAGE' AND TITLE='" + title + "'";
		}
		else
		{
			param_name_string(user);

			if (user.empty() && (user = this->user).empty()) user = "system";
			
			if (dbid.empty()) dbid = this->dbid;

			sqlcmd = "SELECT USER,LEVEL,CONTENT FROM T_XG_CODE WHERE USER='" + user + "' AND FOLDER='" + folder + "' AND TITLE='" + title + "'";
		}
	}
	else
	{
		if (dbid.empty()) dbid = this->dbid;

		sqlcmd = "SELECT USER,LEVEL,CONTENT FROM T_XG_CODE WHERE ID='" + id + "'";
	}
	
	sp<DBConnect> dbconn;

	try
	{
		dbconn = webx::GetDBConnect(dbid);
	}
	catch(Exception e)
	{
		clearResponse();
		
		return XG_SYSBUSY;
	}
	
	sp<QueryResult> rs = dbconn->query(sqlcmd);

	if (!rs)
	{
		clearResponse();
		
		return XG_SYSERR;
	}
	
	sp<RowData> row = rs->next();
		
	if (!row)
	{
		clearResponse();
	
		return XG_OK;
	}

	user = row->getString(0);
	level = row->getString(1);
	content = row->getString(2);

	if (user == this->user || level[0] > '2')
	{
		out << content;
	}

	return XG_OK;
}